<template>
    <n-modal
        :title="title"
        v-model:show="show"
        preset="card"
        @close="close"
        :on-after-enter="() => init()"
    >
        <n-upload
            show-download-button
            list-type="image-card"
            :file-list="records"
            :headers="header"
            :on-before-upload="handleUpload"
            :on-error="handleError"
            :on-remove="handleRemove"
        >
            点击上传
        </n-upload>
        <template #footer>
            <n-space justify="end">
                <n-button @click="close">关闭</n-button>
            </n-space>
        </template>
    </n-modal>
</template>
<script lang="ts" setup>
import { reactive, toRefs } from 'vue'
import { UploadFileInfo } from 'naive-ui'
import { getAttachListByGroupId, postAttach, deleteAttach} from '@/api/file/attach'
import { getToken } from '@/utils/cookie'

const token = getToken()

const state = reactive({
    form: {

    } as Attach,
    header: {
        'Authorization': `Bearer ${token}`
    },
    records: [

    ] as UploadFileInfo[]
})

const {
    form,
    header,
    records
} = toRefs(state)

const props = defineProps({
    title: {
        type: String
    },
    show: {
        type: Boolean
    },
    id: {
        type: String,
        required: true
    }
})

async function handleUpload(e: any){
    const formData = new FormData()
    formData.append('file', e.file.file);
    const { data } = await postAttach(formData)
    state.records.push({
        id: data.id,
        name: data.name,
        status: 'finished',
        url: `http://127.0.0.1:9000/static/${data.name}`
    })
}

async function handleRemove(e: any){
    const { data } = await deleteAttach(e.file.id)
    const index = state.records.findIndex(ele => ele.id = data.id)
    state.records.splice(index, 1)
}

const emits = defineEmits<{
    (e: 'handleCloseOnClick'): void,
    (e: 'handleSelectOnClick'): void
}>()

const init = async () => {
    const { data } = await getAttachListByGroupId(props.id)
    state.records = data.map(ele => ({
        id: ele.id,
        name: ele.name,
        status: 'finished',
        url: `http://127.0.0.1:9000/static/${ele.name}`
    }))
}

const close = () => {
    emits('handleCloseOnClick')
}

function handleError(e: any){
    console.log('upload file', e)
}

</script>